// 获取模块请求接口所需url及端口号
// import { GetDate } from '@/common/JS/common'

// 验证权限
export const getService = (permissions, perStatus, baseURL, childModule) => {
  if (permissions) {
    let name = uni
      .getStorageSync('menuList')
      .filter((list) => list.name === permissions)
    // 针对计件设置特殊处理
    if (name.length > 1) {
      if (perStatus !== 'READ') {
        name = name.find((list) => list.permissios === childModule)
      } else name = name[0]
    } else name = name[0]
    if (name) {
      if (name.allowPermissios.find((data) => data === perStatus)) {
        const port = name.servicePort.toString()
        const http = port.includes('43') ? 'https://' : 'http://'
        return `${http}${name.serviceIp}:${name.servicePort}`
      } else return false
    } else return false
  } else return baseURL
}

// 优惠审批 => 筛选出当前用户可操作的分公司
export const SECURITY_DATA_MATCH = (roleList) => {
  let arr = []
  for (const data of roleList) {
    for (const securityData of data.securityData) {
      // 过滤空值
      if (securityData.permissions[0] !== '') {
        arr = [...arr, ...securityData.permissions]
      }
    }
  }
  return arr
}

// 获取到优惠审批菜单角标
export const GET_BADGE = () => {
  return new Promise((resolve) => {
    uni.$u.api
      .getPaperOrderCountForPreferCheck({
        groupId: uni.getStorageSync('extend').groupId
      })
      .then((res) => {
        resolve(res)
      })
  })
}

// 获取到工资审批菜单角标
export const GET_BADGE_SALARY = () => {
  return new Promise((resolve) => {
    uni.$u.api
      .getApprovalMonthlySalaryCountForPhone({
        groupId: uni.getStorageSync('extend').groupId
      })
      .then((res) => {
        resolve(res)
      })
  })
}

// 获取到支出审批菜单角标
export const GET_BADGE_PAY = () => {
  return new Promise((resolve) => {
    uni.$u.api
      .getApprovalOrderPayOutCountForPhone({
        groupId: uni.getStorageSync('extend').groupId
        // organId: uni.getStorageSync('extend').organId,
      })
      .then((res) => {
        resolve(res)
      })
  })
}

// 获取到支出审批菜单角标
export const GET_BADGE_CREDIT = () => {
  // const date = new GetDate()
  // const orderBeginDate = date.lastMonth.start
  // const orderEndDate = date.lastMonth.end
  // return new Promise((resolve) => {
  //   uni.$u.api
  //     .getCreditApplyForms({
  //       groupId: uni.getStorageSync('extend').groupId,
  //       organId: uni.getStorageSync('extend').organId,
  //       orderBeginDate,
  //       orderEndDate,
  //       yesPhone: 1,
  //       yesChecked: 0,
  //       yesApproved: 0
  //     })
  //     .then((res) => {
  //       resolve(res)
  //     })
  // })
}

// 获取我的待办菜单角标
export const GET_WILLDO = () => {
  return new Promise((resolve) => {
    uni.$u.api
      .getFormReportSql(
        {
          appId: '33605af33ff311ef9ce53868dd107910',
          reportId: '1721304504922',
          values: {
            groupId: uni.getStorageSync('extend').groupId,
            organId: uni.getStorageSync('extend').organId
          }
        },
        'willdo'
      )
      .then((res) => {
        resolve(res)
      })
  })
}

// 获取到需要添加角标的菜单索引 => index
// eslint-disable-next-line no-unused-vars
export const GET_MENULIST_INDEX = (name, list) => {
  for (const [index, list] of list.entries()) {
    if (list.name === name) {
      return index
    }
  }
}

// 翻班组人员排序
export const initialSort = (dataList) => {
  const list = []
  const sortIndex = []
  for (const data of dataList) {
    if (!sortIndex.find((i) => i === data.pinyin)) sortIndex.push(data.pinyin)
  }
  sortIndex.sort((a, b) => a.localeCompare(b))
  // eslint-disable-next-line no-unused-vars
  for (const [index, sort] of sortIndex.entries()) {
    const arr = dataList.filter((i) => i.pinyin === sort)
    const obj = { child: arr }
    list.push(obj)
  }
  return list
}

const getLocalFilePath = (path) => {
  if (
    path.indexOf('_www') === 0 ||
    path.indexOf('_doc') === 0 ||
    path.indexOf('_documents') === 0 ||
    path.indexOf('_downloads') === 0
  ) {
    return path
  }
  if (path.indexOf('file://') === 0) {
    return path
  }
  if (path.indexOf('/storage/emulated/0/') === 0) {
    return path
  }
  if (path.indexOf('/') === 0) {
    var localFilePath = plus.io.convertAbsoluteFileSystem(path)
    if (localFilePath !== path) {
      return localFilePath
    } else {
      path = path.substr(1)
    }
  }
  return '_www/' + path
}

// 获取当前时间，格式2024-07-23 17:32:01
export const formatTime = () => {
  // var currentTime = new Date()
  // var year = currentTime.getFullYear()
  // var month = (currentTime.getMonth() + 1).toString().padStart(2, '0')
  // var day = currentTime.getDate().toString().padStart(2, '0')
  // var hours = currentTime.getHours().toString().padStart(2, '0')
  // var minutes = currentTime.getMinutes().toString().padStart(2, '0')
  // var seconds = currentTime.getSeconds().toString().padStart(2, '0')
  // var currentTimeVal =
  //   year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
  // return currentTimeVal
}

export const formatDate = () => {
  const now = new Date()
  const year = now.getFullYear() // 获取年份
  const month = String(now.getMonth() + 1).padStart(2, '0') // 月份是从0开始的，所以要+1，并使用padStart保证是两位数
  const day = String(now.getDate()).padStart(2, '0') // 获取日，并使用padStart保证是两位数
  return `${year}-${month}-${day}` // 使用模板字符串拼接
}

export const dateInterval = (year, month) => {
  let beginDate = ''
  let endDate = ''
  if (year && month) {
    // 计算当月天数
    const daysInMonth = new Date(year, month, 0).getDate()
    // 补零
    const monthStr = month.toString().padStart(2, '0')
    beginDate = `${year}-${monthStr}-01`
    endDate = `${year}-${monthStr}-${daysInMonth}`
  } else {
    const date = new Date()
    const years = date.getFullYear()
    let months = date.getMonth() + 1
    // 计算当月天数
    const daysMonth = new Date(years, months, 0).getDate()
    // 补零
    months = months.toString().padStart(2, '0')
    beginDate = `${years}-${months}-01`
    endDate = `${years}-${months}-${daysMonth}`
  }
  // 返回结果
  return [beginDate, endDate]
}

// 图片地址转为base64
export const pathToBase64 = (path) => {
  return new Promise(function (resolve, reject) {
    if (typeof window === 'object' && 'document' in window) {
      if (typeof FileReader === 'function') {
        var xhr = new XMLHttpRequest()
        xhr.open('GET', path, true)
        xhr.responseType = 'blob'
        xhr.onload = function () {
          if (this.status === 200) {
            const fileReader = new FileReader()
            fileReader.onload = function (e) {
              resolve(e.target.result)
            }
            fileReader.onerror = reject
            fileReader.readAsDataURL(this.response)
          }
        }
        xhr.onerror = reject
        xhr.send()
        return
      }
      var canvas = document.createElement('canvas')
      var c2x = canvas.getContext('2d')
      var img = new Image()
      img.onload = function () {
        canvas.width = img.width
        canvas.height = img.height
        c2x.drawImage(img, 0, 0)
        resolve(canvas.toDataURL())
        canvas.height = canvas.width = 0
      }
      img.onerror = reject
      img.src = path
      return
    }
    if (typeof plus === 'object') {
      plus.io.resolveLocalFileSystemURL(
        getLocalFilePath(path),
        function (entry) {
          entry.file(
            function (file) {
              var fileReader = new plus.io.FileReader()
              fileReader.onload = function (data) {
                resolve(data.target.result)
              }
              fileReader.onerror = function (error) {
                reject(error)
              }
              fileReader.readAsDataURL(file)
            },
            function (error) {
              reject(error)
            }
          )
        },
        function (error) {
          reject(error)
        }
      )
      return
    }
    if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
      wx.getFileSystemManager().readFile({
        filePath: path,
        encoding: 'base64',
        success: function (res) {
          resolve('data:image/png;base64,' + res.data)
        },
        fail: function (error) {
          reject(error)
        }
      })
      return
    }
    reject(new Error('not support'))
  })
}

// base64转为图片地址
export const base64ToPath = (base64) => {
  return new Promise(function (resolve, reject) {
    if (typeof window === 'object' && 'document' in window) {
      base64 = base64.split(',')
      var type = base64[0].match(/:(.*?);/)[1]
      var str = atob(base64[1])
      var n = str.length
      var array = new Uint8Array(n)
      while (n--) {
        array[n] = str.charCodeAt(n)
      }
      return resolve(
        (window.URL || window.webkitURL).createObjectURL(
          new Blob([array], { type: type })
        )
      )
    }
    // eslint-disable-next-line no-useless-escape
    var extName = base64.match(/data\:\S+\/(\S+);/)
    if (extName) {
      extName = extName[1]
    } else {
      reject(new Error('base64 error'))
    }
    var fileName = Date.now() + '.' + extName
    if (typeof plus === 'object') {
      var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
      bitmap.loadBase64Data(
        base64,
        function () {
          var filePath = '_doc/uniapp_temp/' + fileName
          bitmap.save(
            filePath,
            {},
            function () {
              bitmap.clear()
              resolve(filePath)
            },
            function (error) {
              bitmap.clear()
              reject(error)
            }
          )
        },
        function (error) {
          bitmap.clear()
          reject(error)
        }
      )
      return
    }
    if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
      var filePath = wx.env.USER_DATA_PATH + '/' + fileName
      wx.getFileSystemManager().writeFile({
        filePath: filePath,
        data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
        encoding: 'base64',
        success: function () {
          resolve(filePath)
        },
        fail: function (error) {
          reject(error)
        }
      })
      return
    }
    reject(new Error('not support'))
  })
}
